package com.lh_travel.lohas.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Pair;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.adapter.BaseRecyclerAdapter;
import com.lh_travel.lohas.adapter.ConverPageAdapter;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.CommentIntentBean;
import com.lh_travel.lohas.domain.FilterMessage;
import com.lh_travel.lohas.domain.HotelFilterBean;
import com.lh_travel.lohas.domain.HotelListBean;
import com.lh_travel.lohas.interfaces.PageIndex;
import com.squareup.picasso.Picasso;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxResultCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class HotelMapActivity extends baseActivity {

    private String scope = "1.5";
    private String sore_type = "";
    private String price_type = "";
    private String star_type = "";
    private String theme_type = "";
    private String device_type = "";
    private String position_type = "";
    private String lat ;
    private String lng ;

    private String check_in;
    private String check_out;
    private String keyword;

    private MapView mapview;
    private Toolbar toolbar;
    private AMap map;
    private Marker tempMarker;
    private ViewPager vp_info;
    private BaseRecyclerAdapter<HotelListBean.SimpleHotelBean> infoAdapter;
    private ArrayList<Marker> globalMakerList;
    private int currentIndex;
    private ConverPageAdapter<HotelListBean.SimpleHotelBean> converPageAdapter;
    private ArrayList<HotelListBean.SimpleHotelBean> hotel_lists;
    private ImageButton img_back;
    private TextView tv_search;
    private LatLng latLng;
    private int total_count;
    private CommentIntentBean detailBean;
    private HotelFilterBean filterBean;
    private RelativeLayout rl_filter;
    private TextView tv_filter_result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_hotel_map);

        EventBus.getDefault().register(this);

        mapview = (MapView) findViewById(R.id.mapview);

        //必须要写
        mapview.onCreate(savedInstanceState);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapview.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapview.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapview.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void findView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        vp_info = (ViewPager) findViewById(R.id.vp_info);
        img_back = (ImageButton) findViewById(R.id.img_back);
        tv_search = (TextView) findViewById(R.id.tv_search);
        rl_filter = (RelativeLayout) findViewById(R.id.rl_filter);
        tv_filter_result = (TextView) findViewById(R.id.tv_filter_result);
    }

    @Override
    public void bindListner() {

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        rl_filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(mContext, HotelFilterActivity.class);

                intent.putExtra("detail", filterBean);

                startActivity(intent);
            }
        });
    }

    @Override
    public void ensureUI() {

        detailBean = (CommentIntentBean) getIntent().getSerializableExtra("detail");

        lat = detailBean.lat;

        lng = detailBean.lng;

        check_in = detailBean.checkIn;

        check_out = detailBean.checkOut;

        keyword = detailBean.keyWord;

        setSupportActionBar(toolbar);
        toolbar.setEnabled(true);

        initMap();

        //请求1.5km的酒店信息
        new api(mContext).getHotelMap(lat, lng, scope, sore_type, price_type, star_type, theme_type, device_type,
                position_type, hotelInfo);

        new api(mContext).getConditions(keyword, conditionCallBack);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void filterMessageEvent(FilterMessage message) {
        switch (message.TAG) {

            case "HotelMapActivity":

                sore_type = message.scorePostion;
                price_type = message.pricePostion;
                star_type = message.starPostion;
                theme_type = message.themePostion;
                position_type = message.position;

                filterBean = message.bean;

                //请求1.5km的酒店信息

                new api(mContext).getHotelMap(lat, lng, scope, sore_type, price_type, star_type, theme_type, device_type,
                        position_type, hotelInfo);

                break;
        }
    }

    private void initMap() {

        showViewLoad();

        map = mapview.getMap();
        UiSettings settings = map.getUiSettings();

        settings.setZoomControlsEnabled(false);

        map.moveCamera(CameraUpdateFactory.zoomTo(14));

        latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));

        map.moveCamera(CameraUpdateFactory.changeLatLng(latLng));

        map.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(final CameraPosition cameraPosition) {

                LatLng target = cameraPosition.target;

                if (AMapUtils.calculateLineDistance(target, latLng) > 3000) {

                    tv_search.setText("搜索该区域的酒店");

                    tv_search.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //请求1.5km的酒店信息

                            showViewLoad();

                            new api(mContext).getHotelMap(cameraPosition.target.latitude + "", cameraPosition.target.longitude + "",
                                    scope, sore_type, price_type,
                                    star_type, theme_type, device_type,
                                    position_type, hotelInfo);

                        }
                    });
                } else {

                    tv_search.setText(total_count + "家酒店");

                    tv_search.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            return;
                        }
                    });
                }
            }
        });

    }

    private void addMaker(List<HotelListBean.SimpleHotelBean> makeList) {

        if (globalMakerList == null) {
            globalMakerList = new ArrayList();
        } else {

            globalMakerList.clear();
        }

        latLng = map.getCameraPosition().target;

        map.clear();

        for (int i = 0; i < makeList.size(); i++) {

            HotelListBean.SimpleHotelBean bean = makeList.get(i);

            MarkerOptions markerOptions = new MarkerOptions()
                    .position(new LatLng(Double.parseDouble(bean.lat), Double.parseDouble(bean.lng)))
                    .draggable(false)
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.drawable.maker_small)));

            Marker marker = map.addMarker(markerOptions);
            marker.setObject(i);

            globalMakerList.add(marker);
        }

        map.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                int position = (int) marker.getObject();

                vp_info.setCurrentItem(position);

                return false;
            }
        });

    }

    private void initInfoWindows(ArrayList<HotelListBean.SimpleHotelBean> hotel_list) {

        converPageAdapter = new ConverPageAdapter<HotelListBean.SimpleHotelBean>(mContext, R.layout.item_map, hotel_list, new PageIndex() {
            @Override
            public int getIndex() {
                return currentIndex;
            }
        }) {
            @Override
            public void convert(View view, final HotelListBean.SimpleHotelBean item, int position) {

                TextView tv_distent = view.findViewById(R.id.tv_distent);
                final TextView name = view.findViewById(R.id.tv_name);
                TextView tv_position = view.findViewById(R.id.tv_position);
                TextView tv_comment = view.findViewById(R.id.tv_comment);
                TextView tv_discount_price = view.findViewById(R.id.tv_discount_price);
                TextView tv_ori_price = view.findViewById(R.id.tv_ori_price);
                TextView tv_discount = view.findViewById(R.id.tv_discount);
                ImageView img_pic = view.findViewById(R.id.img_pic);
                LinearLayout ll_main = view.findViewById(R.id.ll_main);
                LinearLayout container = view.findViewById(R.id.ll_star_container);
                //优惠
                double value = new BigDecimal(item.rate).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                tv_distent.setText(item.distance + "km");
                name.setText(item.title);
                tv_position.setText("距离" + item.position_name + item.pos_distance + "km");
                tv_comment.setText(item.fake_comment + item.fake_comment_score + "/" + item.fake_comment_num + "评论");

                switch (item.star) {
                    case "豪华":

                        setStar(5, container);

                        break;

                    case "高档":

                        setStar(4, container);

                        break;

                    case "舒适":

                        setStar(3, container);

                        break;

                    case "经济":

                        setStar(2, container);

                        break;
                }

                if (item.min_price.equals("满房")) {
                    tv_discount_price.setText("已满房");
                    tv_ori_price.setVisibility(View.GONE);

                } else {

                    tv_discount_price.setText("¥" + item.min_price);
                    tv_ori_price.setText("¥" + item.max_price);
                    tv_ori_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    tv_ori_price.setVisibility(View.VISIBLE);
                }

                if (value > 0.1) {
                    tv_discount.setText("优惠" + ((int) (value * 100)) + "%");
                    tv_discount.setVisibility(View.VISIBLE);

                } else {
                    tv_discount.setVisibility(View.GONE);
                }

                if (item.picture != null && item.picture.length() > 0) {
                    Picasso.with(mContext).load(item.picture + "?x-oss-process=image/resize,p_30").
                            placeholder(R.drawable.default_bg200x200).
                            //error(R.drawable.default_bg100x100).
                                    fit().centerCrop().
                            into(img_pic);
                }

                ll_main.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent(mContext, HotelDetailActivity.class);

                        CommentIntentBean bean = new CommentIntentBean();

                        bean.belong = item.belong;
                        bean.id = item.id;
                        bean.checkIn = check_in;
                        bean.checkOut = check_out;

                        intent.putExtra("detail", bean);
                        intent.putExtra("star", item.star);

                        mContext.startActivity(intent, ActivityOptions.makeSceneTransitionAnimation((Activity) mContext,
                                /*new Pair<View, String>(img, "TRANSITIONIMAGE"),*/ new Pair<View, String>(name, "TRANSITIONTITLE")).toBundle());

                    }
                });

            }
        };
        vp_info.setPageMargin(20);

        vp_info.setAdapter(converPageAdapter);

        vp_info.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                currentIndex = position;

                Marker marker = globalMakerList.get(position);

                map.moveCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));

                marker.setToTop();


                tempMarker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(), R.drawable.maker_small)));


                tempMarker = marker;

                marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(), R.drawable.maker_big)));

                //网络请求---------假如没请求过的就请求,然后在字段time中添加当前的时间戳,那么再次请求就判断是不是在半小时内的

                if (hotel_lists.get(position).time == null) {
                    showViewLoad();
                    new api(mContext).getHotelone(check_in, check_out, hotel_lists.get(position).belong, hotel_lists.get(position).id, mapOneCallBack);

                } else if (System.currentTimeMillis() - hotel_lists.get(position).time > (30 * 60 * 1000)) {
                    showViewLoad();

                    new api(mContext).getHotelone(check_in, check_out, hotel_lists.get(position).belong, hotel_lists.get(position).id, mapOneCallBack);

                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        setVPFirstSt();

    }

    private void setStar(int count, LinearLayout container) {

        container.removeAllViews();

        for (int i = 0; i < count; i++) {

            View view = View.inflate(mContext, R.layout.item_stars, null);

            container.addView(view);

        }
    }

    private void setVPFirstSt() {
        Marker marker = globalMakerList.get(0);
        map.moveCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));

        marker.setToTop();

        tempMarker = marker;

        marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.maker_big)));

        new api(mContext).getHotelone(check_in, check_out, hotel_lists.get(0).belong, hotel_lists.get(0).id, mapOneCallBack);
    }

    private RxResultCallback<HotelListBean> hotelInfo = new RxResultCallback<HotelListBean>() {
        @Override
        public void onNext(Object tag, int code, String message, HotelListBean response) {

            if (hotel_lists == null) {
                hotel_lists = new ArrayList<>();

            } else {
                hotel_lists.clear();
            }

            if (code == 200){

                if (response.hotel_list.size() > 0) {

                    hotel_lists.addAll(response.hotel_list);

                    total_count = response.total_count;

                    tv_search.setText(total_count + "家酒店");

                    tv_filter_result.setText("刷选结果 共" + response.total_count + "家酒店");

                } else {

                    dismissViewLoad();
                    tv_search.setText("没搜索到该区域的酒店");
                }

            }else if (code == 401 || code == 101){

                dismissViewLoad();
                tv_filter_result.setText("刷选结果共 0 家酒店");

            }

            addMaker(hotel_lists);
            initInfoWindows(hotel_lists);
        }

        @Override
        public void onError(Object tag, Throwable e) {
            dismissViewLoad();
        }

        @Override
        public void onCancel(Object tag, Throwable e) {
            dismissViewLoad();
        }
    };

    private RxResultCallback<HotelListBean.SimpleHotelBean> mapOneCallBack = new RxResultCallback<HotelListBean.SimpleHotelBean>() {
        @Override
        public void onNext(Object tag, int code, String message, HotelListBean.SimpleHotelBean response) {

            hotel_lists.get(currentIndex).min_price = response.min_price_1;
            hotel_lists.get(currentIndex).max_price = response.max_price;
            hotel_lists.get(currentIndex).third_url = response.third_url;
            hotel_lists.get(currentIndex).time = System.currentTimeMillis();

            converPageAdapter.notifyDataSetChanged();

            dismissViewLoad();
        }

        @Override
        public void onError(Object tag, Throwable e) {
            dismissViewLoad();
        }

        @Override
        public void onCancel(Object tag, Throwable e) {
            dismissViewLoad();
        }
    };

    private RxResultCallback<HotelFilterBean> conditionCallBack = new RxResultCallback<HotelFilterBean>() {
        @Override
        public void onNext(Object tag, int code, String message, HotelFilterBean response) {

            filterBean = response;
            filterBean.id = "HotelMapActivity";

        }

        @Override
        public void onError(Object tag, Throwable e) {

        }

        @Override
        public void onCancel(Object tag, Throwable e) {

        }
    };
}
